package org.jeecg.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.jeecg.common.converter.IeMappingJackson2HttpMessageConverter;
import org.jeecg.common.filter.RequestNullParametersFilter;

import org.jeecg.common.system.properties.FileUploadProperties;
import org.jeecg.common.system.properties.HhicProperties;
import org.jeecg.config.interceptor.LoginInterceptor;
import org.jeecg.modules.shiro.authc.interceptor.OnlineInterceptor;
import org.jeecg.modules.shiro.authc.interceptor.XssInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * Spring Boot 2.0 解决跨域问题
 *
 * @Author qinfeng
 */
@Configuration
@EnableConfigurationProperties(value = {HhicProperties.class, FileUploadProperties.class})
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @Value("${jeecg.path.webapp}")
    private String webAppPath;

    @Value("${spring.resource.static-locations}")
    private String staticLocations;

    @Autowired
    private XssInterceptor xssInterceptor;

    @Autowired
    private RequestNullParametersFilter requestNullParametersFilter;
    @Autowired
    private LoginInterceptor loginInterceptor;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        //自定义ie消息转换器 必须在jackson消息转换器之前执行
        converters.set(7, new IeMappingJackson2HttpMessageConverter(objectMapper));
    }

    @Bean
    public FilterRegistrationBean xssFilterRegistration() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(requestNullParametersFilter);
        registrationBean.addUrlPatterns("/*");
        registrationBean.setName("requestNullParametersFilter");
        registrationBean.setOrder(0);
        registrationBean.setEnabled(true);
        return registrationBean;
    }

    @Bean
    public OnlineInterceptor onlineInterceptor() {
        return new OnlineInterceptor();
    }

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /* 是否允许请求带有验证信息 */
        corsConfiguration.setAllowCredentials(true);
        /* 允许访问的客户端域名 */
        corsConfiguration.addAllowedOrigin("*");
        /* 允许服务端访问的客户端请求头 */
        corsConfiguration.addAllowedHeader("*");
        /* 允许访问的方法名,GET POST等 */
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

    /**
     * 静态资源的配置 - 使得可以从磁盘中读取 Html、图片、视频、音频等
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("file:" + upLoadPath + "//", "file:" + webAppPath + "//").addResourceLocations(staticLocations.split(","));
    }

    /**
     * 方案一： 默认访问根路径跳转 doc.html页面 （swagger文档页面）
     * 方案二： 访问根路径改成跳转 index.html页面 （简化部署方案： 可以把前端打包直接放到项目的 webapp，上面的配置）
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("doc.html");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String[] exculudes = new String[]{"/*.html", "/html/**", "/js/**", "/css/**", "/images/**", "/templates/**"};
        registry.addInterceptor(onlineInterceptor()).excludePathPatterns(exculudes).addPathPatterns("/online/cgform/api/**");
        registry.addInterceptor(xssInterceptor).excludePathPatterns(exculudes).addPathPatterns("/**");
        String [] includes = new String[]{
                "/personal/v1/**","/personal/top/**"};
        registry.addInterceptor(loginInterceptor).order(1).excludePathPatterns(exculudes).addPathPatterns(includes);
    }
}
